import jdk.nashorn.internal.ir.IdentNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mac
 * Date: 2022-09-28
 * Time: 8:25
 */
class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}
public class TestDemo {
    //236.二叉树的最近公共祖先

    /**
     * 思路一：假定它是一颗二叉搜索树推广到二叉树
     * @param root
     * @param p
     * @param q
     * @return root
     */
    //思路1：
      //如果给定的树是一颗二叉搜索树
      //中序遍历的大小是有序的
      //根节点的左树 都比根小
      //根节点的右树 都比根大
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null){
            return null;
        }

        if (root == p || root == q){
            return root;
        }
        /*if (p.val < root.val && q.val < root.val){
            return lowestCommonAncestor(root.left, p, q);
        }
        if (p.val > root.val && q.val > root.val){
            return lowestCommonAncestor(root.right, p, q);
        }
        if (p.val > root.val && q.val < root.val){
            return root;
        }*/

        TreeNode leftT = lowestCommonAncestor(root.left,p,q);
        TreeNode rightT = lowestCommonAncestor(root.right,p,q);

        if (leftT != null && rightT != null){
            return root;
        }else if (leftT != null){
            return leftT;
        }else{
            return rightT;
        }
    }

    //思路二：链表求交点
    //1.两个栈存储路径
    //2.求栈的大小
    //3.让栈中多的元素，出差值个元素
    //4.开始出栈，直到栈顶元素相同，此时就是公共祖先

    //root:根节点        node:指定节点   stack:存放从根节点到指定节点的路径
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack){
        if (root == null || node == null) return false;

        stack.push(root);

        if (root == node) return true;

        boolean flg = getPath(root.left ,node, stack);
        if (flg){
            return true;
        }

        flg = getPath(root.right ,node, stack);
        if (flg){
            return true;
        }
        stack.pop();
        return false;
    }
    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root, p, stack1);
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,q,stack2);
        int size1 = stack1.size();
        int size2 = stack2.size();
        if (size1 > size2){
            int size = size1 - size2;
            while(size != 0){
                stack1.pop();
                size--;
            }
            while (!stack1.empty() && !stack2.empty()){
                if (stack1.peek() == stack2.peek()){
                    return stack1.pop();
                }else{
                    stack1.pop();
                    stack2.pop();
                }
            }
        }else{
            int size = size2 - size1;
            while(size != 0){
                stack2.pop();
                size--;
            }
            while (!stack1.empty() && !stack2.empty()){
                if (stack1.peek() == stack2.peek()){
                    return stack1.pop();
                }else{
                    stack1.pop();
                    stack2.pop();
                }
            }
        }
        return null;
    }

    //牛客 - JZ36 二叉搜索树与双向链表
    //1.排序：中序遍历
    //2.双向链表：难点
    TreeNode prev = null;
    public void inOrder(TreeNode pCur){
        if (pCur == null) return;

        inOrder(pCur.left);
        //打印
        pCur.left = prev;
        if (prev != null){
            prev.right = pCur;
        }
        prev = pCur;
        inOrder(pCur.right);
    }
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) return null;
        inOrder(pRootOfTree);

        TreeNode node = pRootOfTree;
        while (node.left != null){
            node = node.left;
        }
        return node;
    }

    //105.从前序遍历和中序遍历构建二叉树

    /*public int preIndex = 0;//回溯过程会改变其值
    public TreeNode createTreeByPandI(int[] preorder, int[] inorder,int inbegin, int inend){
        if (inbegin > inend){
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);
        int rootIndex = findIndexOfI(inorder,inbegin,inend,preorder[preIndex]);
        if (rootIndex == -1){
            return null;
        }
        preIndex++;
        root.left = createTreeByPandI(preorder, inorder,inbegin,rootIndex - 1);
        root.right = createTreeByPandI(preorder,inorder, rootIndex + 1, inend);
        return root;
    }
    private int findIndexOfI(int[] inorder,int inbegin, int inend, int key){
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key){
                return i;
            }
        }
        return -1;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) return null;

        return createTreeByPandI(preorder, inorder,0,inorder.length - 1);
    }*/

    //106.从中序与后序遍历构造二叉树
    public int postIndex = 0;//回溯过程会改变其值
    public TreeNode createTreeByPandI(int[] inorder, int[] postorder,int inbegin, int inend){
        if (inbegin > inend){
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = findIndexOfI(inorder,inbegin,inend,postorder[postIndex]);
        if (rootIndex == -1){
            return null;
        }
        postIndex--;
        root.right = createTreeByPandI(inorder, postorder,rootIndex + 1,inend);
        root.left = createTreeByPandI(inorder,postorder, inbegin, rootIndex - 1);
        return root;
    }
    private int findIndexOfI(int[] inorder,int inbegin, int inend, int key){
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key){
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (postorder == null || inorder == null) return  null;
        postIndex = postorder.length - 1;

        return createTreeByPandI(inorder,postorder,0,inorder.length - 1);
    }

    //606.根据二叉树创建字符串

    public void treeToString(TreeNode t, StringBuilder sb){
        if (t == null) return;
        sb.append(t.val);

        if (t.left != null){
            sb.append("(");
            treeToString(t.left,sb);
            sb.append(")");
        }else{
            if (t.right == null){
                return;
            }else{
                sb.append("()");
            }
        }
        if (t.right == null){
            return;
        }else{
            sb.append("(");
            treeToString(t.right,sb);
            sb.append(")");
        }
    }
    public String tree2str(TreeNode root) {
        if (root == null){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        treeToString(root,sb);
        return sb.toString();
    }

    //144.非递归前序创建二叉树
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }

        return list;
    }

    //94.非递归中序创建二叉树
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            list.add(top.val);
            cur = top.right;
        }

        return list;
    }

    //145.非递归后序创建二叉树
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            //如果当前节点右子树被遍历过，可以直接弹出
            if (top.right == null || top.right == prev){
                stack.pop();
                list.add(top.val);
                prev = top;//记录最近一次打印节点
            }else{
                cur = top.right;
            }
        }

        return list;
    }
}
